package com.example.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.utils.Base64Util.Base64;
import com.example.springboot.common.utils.ImageCodeUtil.ImageCodeUtil;
import com.example.springboot.common.utils.Md5Util.Md5Util;
import com.example.springboot.common.utils.RedisUtil.RedisUtil;
import com.example.springboot.common.utils.StringUtils.StringUtils;
import com.example.springboot.common.utils.ThrowUtil.ThrowUtil;
import com.example.springboot.common.utils.UUIDUtil.UUIDUtils;
import com.example.springboot.common.utils.UserHolder.UserHolderUtil;
import com.example.springboot.entity.LoginUser;
import com.example.springboot.entity.Permission;
import com.example.springboot.entity.User;
import com.example.springboot.entity.vo.RouterVo;
import com.example.springboot.mapper.LoginMapper;
import com.example.springboot.entity.dto.LoginDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;


import javax.imageio.ImageIO;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.springboot.common.constants.Constants.*;
import static com.example.springboot.common.utils.UserHolder.UserHolderUtil.*;
import static com.example.springboot.service.TokenService.MILLIS_MINUTE;


@Service
public class LoginService {
    // 令牌有效期（默认60分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 登录
     */
    public String login(LoginDto loginDto) {
        // 验证码校验
        validateCaptcha(loginDto);
        User user = matches(loginDto);
        String token = UUIDUtils.fastUUID();
        //缓存数据
        redisCache(user, token);
        return tokenService.createToken(token);
    }

    private void redisCache(User user, String token) {
        List<Long> role = roleService.getRoleByUserId(user.getId());
        List<String> permissions = permissionService.findMenuNameByRoleId(role.get(0));
        LoginUser loginUser = LoginUser.builder()
                .user(user)
                .token(token)
                .roles(role)
                .permissions(permissions)
                .loginTime(System.currentTimeMillis())
                .expireTime(System.currentTimeMillis() + expireTime * MILLIS_MINUTE)
                .build();
        redisUtil.setCacheObject(USER_REDIS + token, loginUser, USER_REDIS_OVERTIME, TimeUnit.MINUTES);
    }

    private User matches(LoginDto loginDto) {
        ThrowUtil.throwIf(StrUtil.isBlank(loginDto.getUsername()) || StrUtil.isBlank(loginDto.getPassword()), "用户名和密码都不能为空!");
        //对密码进行加密
        loginDto.setPassword(Md5Util.encode(loginDto.getPassword()));
        User user = User.builder().username(loginDto.getUsername()).password(loginDto.getPassword()).build();
        User one = loginMapper.getOne(user);
        ThrowUtil.throwIf(StringUtils.isNull(one), USER_LOGIN_FALSE);
        return one;
    }

    private void validateCaptcha(LoginDto loginDto) {
        String cacheCode = redisUtil.getCacheObject(CODE_REDIS + loginDto.getUuid());
        ThrowUtil.throwIf(StringUtils.isEmpty(cacheCode), "验证码过期，请重新输入");
        ThrowUtil.throwIf(!cacheCode.equalsIgnoreCase(loginDto.getCheckcode()), CODE_LOGIN_FALSE);
    }


    /**
     * 获取用户信息
     */
    public Map<String, Object> info() {
        Map<String, Object> map = new HashMap<>();
        List<RouterVo> routerList = permissionService.findUserMenuListByUserId(getUserId());
        map.put("user", getUser());
        map.put("roles", getRoles());
        map.put("permissions", getPermissions());
        map.put("routers", routerList);
        return map;
    }

    public Map<String, Object> checkCode() {
        ImageCodeUtil vCode = new ImageCodeUtil(115, 31, 4, 10);

        String code = vCode.getCode();
        String uuid = UUIDUtils.simpleUUID();
        redisUtil.setCacheObject(CODE_REDIS + uuid, code, CODE_REDIS_OVERTIME, TimeUnit.MINUTES);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(vCode.getBuffImg(), "jpg", os);
        } catch (IOException e) {
            ThrowUtil.throwIf(e.getMessage());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return map;
    }
}
